﻿'
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2011
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
'

Imports System.Web.UI
Imports System.Collections.Generic
Imports DotNetNuke.Entities.Users
Imports DotNetNuke.Entities.Tabs
Imports DotNetNuke.Services.Exceptions
Imports DotNetNuke.Services.Localization
Imports System.Xml
Imports System.IO
Imports Telerik.Web.UI
Imports DotNetNuke.Entities.Portals
Imports DotNetNuke.Services.FileSystem
Imports DotNetNuke.UI.WebControls

Namespace DotNetNuke.Providers.RadEditorProvider

    Partial Class ProviderConfig
        Inherits Entities.Modules.PortalModuleBase
        Implements Entities.Modules.IActionable

#Region "Private Members"""

        Private Const htmlEditorNode As String = "/configuration/dotnetnuke/htmlEditor"
        Private Const spellCheckRootNodeIIS6 As String = "/configuration/system.web"
        Private Const spellCheckRootNodeIIS7 As String = "/configuration/system.webServer"
        Private Const radEditorProviderName As String = "DotNetNuke.RadEditorProvider"

        Private _dnnConfig As XmlDocument
        Private _defaultconfig As List(Of ConfigInfo)

#End Region

        Protected ReadOnly Property DefaultConfig() As List(Of ConfigInfo)
            Get
                If Not DotNetNuke.Common.Utilities.DataCache.GetCache("RAD_DEFAULT_CONFIG") Is Nothing Then
                    _defaultconfig = CType(DotNetNuke.Common.Utilities.DataCache.GetCache("RAD_DEFAULT_CONFIG"), List(Of ConfigInfo))
                End If

                If _defaultconfig Is Nothing Then
                    _defaultconfig = InitializeDefaultConfig()
                    DotNetNuke.Common.Utilities.DataCache.SetCache("RAD_DEFAULT_CONFIG", _defaultconfig)
                End If

                Return _defaultconfig

            End Get
        End Property

        Protected ReadOnly Property DNNConfig() As XmlDocument
            Get
                If _dnnConfig Is Nothing Then
                    Dim currentUser As UserInfo = UserController.GetCurrentUserInfo()
                    If (Not currentUser Is Nothing AndAlso currentUser.IsSuperUser) Then
                        _dnnConfig = Config.Load()
                    End If
                End If

                Return _dnnConfig
            End Get
        End Property

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            DotNetNuke.Framework.AJAX.RegisterScriptManager()
            BindConfigForm()
        End Sub

        Protected Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Try

                'If Not ViewState("EditorConfigPath") Is Nothing Then
                '    Dim path As String = CType(ViewState("EditorConfigPath"), String)
                '    BindSelectedConfig(path)
                'End If

                Me.pnlSelectProvider.Visible = False

                If Request.IsAuthenticated Then
                    If UserInfo.IsSuperUser Then

                        Me.pnlSelectProvider.Visible = True
                        ' No reason to show purpose of module, inconsistent w/ rest of UI (in other modules, parts of core)
                        'DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("lblNote", LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.YellowWarning)

                        If (Not IsPostBack) Then
                            BindEditorList()
                        End If

                        BindCurrentEditor()

                        If Not Page.IsPostBack Then
                            LoadConfiguration()
                            LoadPages()
                        End If

                    Else
                        DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("lblHostOnly", LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                    End If
                Else
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("lblNotAuthorized", LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                End If

            Catch exc As Exception
                ProcessModuleLoadException(Me, exc)
            End Try
        End Sub

        Protected Sub treeTools_NodeClick(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEventArgs) Handles treeTools.NodeClick
            BindFile()
        End Sub

        Protected Sub OnUpdateClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click
            Dim orgConfigPath As String = Me.treeTools.SelectedNode.Value
            Dim orgToolsPath As String = orgConfigPath.ToLower.Replace("config", "tools")

            UpdateConfig(orgConfigPath)

            Dim tw As System.IO.StreamWriter = System.IO.File.CreateText(orgToolsPath)
            tw.Write(txtTools.Text)
            tw.Close()
            tw.Dispose()

            DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, "The update was successful.", Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess)
            'BindFile()
        End Sub

        Protected Sub OnCancelClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
            pnlEditor.Visible = False
            pnlForm.Visible = False
            'ulActions.Visible = False

            LoadConfiguration()
            LoadPages()

            DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, "All unsaved changes have been discarded.", Skins.Controls.ModuleMessage.ModuleMessageType.BlueInfo)
        End Sub

        Protected Sub OnCopyClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCopy.Click
            pnlEditor.Visible = False
            pnlForm.Visible = True
            Me.cmdCreate.Visible = True
            rblMode.SelectedIndex = 0

            If treeTools.SelectedNode.Text.StartsWith("Everyone") Then
                rblMode.SelectedIndex = 1
            ElseIf treeTools.SelectedNode.Text.StartsWith("Users") Then
                rblMode.SelectedIndex = 2
            ElseIf treeTools.SelectedNode.Text.StartsWith("Admin") Then
                rblMode.SelectedIndex = 3
            End If
        End Sub

        Protected Sub OnDeleteClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
            Dim orgConfigPath As String = Me.treeTools.SelectedNode.Value
            Dim orgToolsPath As String = orgConfigPath.ToLower.Replace("config", "tools")

            If Not orgConfigPath.ToLower.EndsWith("configfile.xml") Then
                System.IO.File.Delete(orgConfigPath)
                System.IO.File.Delete(orgToolsPath)
            End If

            pnlEditor.Visible = False
            pnlForm.Visible = False
            LoadConfiguration()
            LoadPages()
        End Sub

        Private Sub cmdCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCreate.Click
            Dim orgConfigPath As String = Me.treeTools.SelectedNode.Value
            Dim orgToolsPath As String = orgConfigPath.ToLower.Replace("config", "tools")

            Dim newConfigPath As String = Server.MapPath(Me.TemplateSourceDirectory) & "\ConfigFile\ConfigFile"
            Dim newToolsPath As String = Server.MapPath(Me.TemplateSourceDirectory) & "\ToolsFile\ToolsFile"

            If rblMode.SelectedValue <> "" Then
                newConfigPath += "." & rblMode.SelectedValue
                newToolsPath += "." & rblMode.SelectedValue
            End If

            If chkPortal.Checked Then
                newConfigPath += ".PortalId." & PortalSettings.PortalId.ToString
                newToolsPath += ".PortalId." & PortalSettings.PortalId.ToString
            Else
                If Not treePages.SelectedNode Is Nothing Then
                    newConfigPath += ".TabId." & treePages.SelectedNode.Value
                    newToolsPath += ".TabId." & treePages.SelectedNode.Value
                End If
            End If

            newConfigPath += ".xml"
            newToolsPath += ".xml"

            If Not System.IO.File.Exists(newConfigPath) Then
                System.IO.File.Copy(orgConfigPath, newConfigPath, True)
            End If

            If Not System.IO.File.Exists(newToolsPath) Then
                System.IO.File.Copy(orgToolsPath, newToolsPath, True)
            End If

            'reload tree    
            LoadConfiguration()

            'select new config
            Me.treeTools.FindNodeByValue(newConfigPath).Selected = True

            're-bind new config
            BindFile()
        End Sub

        Protected Sub chkPortal_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkPortal.CheckedChanged
            divTabs.Visible = (chkPortal.Checked = False)
        End Sub

        Protected Sub btnEnable_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnEnable.Click
            Select Case editorList.SelectedValue
                Case radEditorProviderName
                    EnableRadEditor()
                    Exit Select
                Case Else
                    EnableOtherEditor(editorList.SelectedValue)
                    Exit Select
            End Select
        End Sub

#Region "Private Methods"

        Private Sub EnableOtherEditor(ByVal name As String)
            Dim xmlConfig As XmlDocument = DNNConfig

            If (Not xmlConfig Is Nothing AndAlso Not xmlConfig.DocumentElement Is Nothing) Then

                Dim editorProviderNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode(htmlEditorNode)
                editorProviderNode.Attributes("defaultProvider").Value = name
                editorState.Text = name

                Dim radNode As XmlNode = editorProviderNode.SelectSingleNode("providers/add[@name='" & radEditorProviderName & "']")
                If (Not radNode Is Nothing) Then
                    radNode.ParentNode.RemoveChild(radNode)
                End If

                Config.Save(xmlConfig)

                BindCurrentEditor()

            End If
        End Sub

        Private Sub EnableRadEditor()
            Dim xmlConfig As XmlDocument = DNNConfig

            If (Not xmlConfig Is Nothing AndAlso Not xmlConfig.DocumentElement Is Nothing) Then
                Dim editorProviderNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode(htmlEditorNode)
                editorProviderNode.Attributes("defaultProvider").Value = radEditorProviderName
                'check if already added and if not, add definition
                Dim radNode As XmlNode = editorProviderNode.SelectSingleNode("providers/add[@name='" & radEditorProviderName & "']")
                If (radNode Is Nothing) Then
                    radNode = xmlConfig.CreateElement("add")
                    Dim xmlAttr As XmlAttribute = xmlConfig.CreateAttribute("name")
                    xmlAttr.Value = radEditorProviderName
                    radNode.Attributes.Append(xmlAttr)
                    xmlAttr = xmlConfig.CreateAttribute("type")
                    xmlAttr.Value = "DotNetNuke.Providers.RadEditorProvider.EditorProvider, DotNetNuke.RadEditorProvider"
                    radNode.Attributes.Append(xmlAttr)
                    xmlAttr = xmlConfig.CreateAttribute("providerPath")
                    xmlAttr.Value = "~/DesktopModules/Admin/RadEditorProvider"
                    radNode.Attributes.Append(xmlAttr)
                    editorProviderNode.SelectSingleNode("providers").AppendChild(radNode)
                End If

                Config.Save(xmlConfig)

                BindCurrentEditor()

            End If
        End Sub

        Private Sub DisableRadEditor()
            Dim xmlConfig As XmlDocument = DNNConfig

            If (Not xmlConfig Is Nothing AndAlso Not xmlConfig.DocumentElement Is Nothing) Then
                Dim editorProviderNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode(htmlEditorNode)
                'check if already added and if not, add definition
                Dim radNode As XmlNode = editorProviderNode.SelectSingleNode("providers/add[@name='" & radEditorProviderName & "']")
                If (Not radNode Is Nothing) Then
                    radNode.ParentNode.RemoveChild(radNode)
                End If

                Config.Save(xmlConfig)

                BindCurrentEditor()
            End If
        End Sub

        Private Sub BindCurrentEditor()
            Dim editorType As String = GetSelectedEditor()
            editorState.Text = editorType

            'Me.pnlTabContent.Visible = (editorType = radEditorProviderName)

            'If editorType = radEditorProviderName Then
            '    pnlTabContent.Visible = True
            'End If
        End Sub

        Private Sub BindEditorList()
            editorList.DataSource = GetEditorsList()
            editorList.DataBind()

            Dim current As String = GetSelectedEditor()
            Dim item As ListItem = editorList.Items.FindByText(current)
            If (Not item Is Nothing) Then
                editorList.SelectedIndex = -1
                item.Selected = True
            End If
        End Sub

        Private Function GetEditorsList() As List(Of String)
            Dim editors As New List(Of String)()
            Dim xmlConfig As XmlDocument = DNNConfig
            If (Not xmlConfig Is Nothing AndAlso Not xmlConfig.DocumentElement Is Nothing) Then
                Dim editorNodes As XmlNodeList = xmlConfig.DocumentElement.SelectNodes(htmlEditorNode + "/providers/add")
                If (Not editorNodes Is Nothing) Then
                    Dim i As Integer = 0
                    While (i < editorNodes.Count)
                        Dim node As XmlNode = editorNodes.Item(i)
                        If (Not node.Attributes("name") Is Nothing) Then
                            editors.Add(node.Attributes("name").Value)
                        End If
                        i = i + 1
                    End While
                End If
            End If

            If (Not editors.Contains(radEditorProviderName)) Then
                editors.Add(radEditorProviderName)
            End If

            Return editors
        End Function

        Private Function GetSelectedEditor() As String
            Dim xmlConfig As XmlDocument = DNNConfig

            If (Not xmlConfig Is Nothing AndAlso Not xmlConfig.DocumentElement Is Nothing) Then
                Dim editorProviderNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode(htmlEditorNode)
                Return editorProviderNode.Attributes("defaultProvider").Value
            End If

            Return ""
        End Function

        Private Sub UpdateConfig(ByVal strPath As String)
            Dim xmlConfig As New XmlDocument
            xmlConfig.Load(strPath)

            Dim rootNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode("/configuration")
            Dim setting As String = Null.NullString
            Dim currentConfig As List(Of ConfigInfo) = DefaultConfig

            For Each objConfig As ConfigInfo In currentConfig

                If objConfig.IsSeparator = False Then
                    Select Case objConfig.Key.ToLower
                        Case "stripformattingoptions", "contentfilters"
                            Dim ctl As CheckBoxList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), CheckBoxList)

                            If Not ctl Is Nothing Then
                                Try
                                    Dim strSetting As String = ""
                                    Dim blnAllSelected As Boolean = True
                                    For Each item As ListItem In ctl.Items
                                        If item.Selected Then
                                            strSetting += item.Value & ","
                                        Else
                                            blnAllSelected = False
                                        End If
                                    Next
                                    If blnAllSelected Then
                                        If objConfig.Key.ToLower = "stripformattingoptions" Then
                                            strSetting = "All"
                                        Else
                                            strSetting = "DefaultFilters"
                                        End If
                                    Else
                                        If strSetting.EndsWith(",") Then
                                            strSetting = strSetting.Substring(0, strSetting.Length - 1)
                                        End If
                                        If strSetting = "" Then
                                            strSetting = "None"
                                        End If
                                    End If

                                    setting = strSetting

                                Catch
                                End Try
                            End If
                        Case "toolbarmode"
                            Dim ctl As RadioButtonList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), RadioButtonList)

                            If Not ctl Is Nothing Then
                                Try
                                    setting = ctl.SelectedValue
                                Catch
                                End Try
                            End If
                        Case "editmodes"
                            Dim ctl As CheckBoxList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), CheckBoxList)

                            If Not ctl Is Nothing Then
                                Try
                                    Dim strSetting As String = ""
                                    Dim blnAllSelected As Boolean = True
                                    For Each item As ListItem In ctl.Items
                                        If item.Selected Then
                                            strSetting += item.Value & ","
                                        Else
                                            blnAllSelected = False
                                        End If
                                    Next
                                    If blnAllSelected Then
                                        strSetting = "All"
                                    Else
                                        If strSetting.EndsWith(",") Then
                                            strSetting = strSetting.Substring(0, strSetting.Length - 1)
                                        End If
                                        If strSetting = "" Then
                                            strSetting = "All"
                                        End If
                                    End If

                                    setting = strSetting

                                Catch
                                End Try
                            End If
                        Case "imagespath", "mediapath", "documentspath", "flashpath", "silverlightpath", "templatepath"
                            Dim ctl As DropDownList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), DropDownList)

                            If Not ctl Is Nothing Then
                                Try
                                    setting = ctl.SelectedValue
                                Catch
                                End Try
                            End If
                        Case "skin", "contentareamode"
                            Dim ctl As DropDownList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), DropDownList)

                            If Not ctl Is Nothing Then
                                Try
                                    setting = ctl.SelectedValue
                                Catch
                                End Try
                            End If
                        Case "borderwidth", "maxflashsize", "height", "maxsilverlightsize", "maxtemplatesize", "maximagesize", "width", "maxdocumentsize", "maxmediasize", "toolswidth"
                            Dim ctl As RadNumericTextBox = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), RadNumericTextBox)

                            If Not ctl Is Nothing Then
                                Try
                                    setting = ctl.Value.ToString.Replace(".00", "").Replace(".0", "")
                                Catch
                                End Try
                            End If
                        Case "enableresize", "linksusetabnames", "allowscripts", "showportallinks", "autoresizeheight", "linksuserelativeurls", "dmxintegration", "newlinebr"
                            Dim ctl As CheckBox = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), CheckBox)

                            If Not ctl Is Nothing Then
                                Try
                                    setting = ctl.Checked.ToString
                                Catch
                                End Try
                            End If
                        Case Else
                            Dim ctl As TextBox = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), TextBox)

                            If Not ctl Is Nothing Then
                                Try
                                    setting = ctl.Text
                                Catch
                                End Try
                            End If
                    End Select

                    'look for setting node
                    Dim configNode As XmlNode = rootNode.SelectSingleNode("property[@name='" & objConfig.Key & "']")
                    If Not configNode Is Nothing Then
                        'node found, remove it
                        rootNode.RemoveChild(configNode)
                    End If

                    configNode = xmlConfig.CreateElement("property")
                    Dim xmlAttr As XmlAttribute = xmlConfig.CreateAttribute("name")
                    xmlAttr.Value = objConfig.Key
                    configNode.Attributes.Append(xmlAttr)

                    Dim settingnode As XmlNode
                    If setting.Contains(";") Then
                        Dim newsettings As String() = setting.Split(Char.Parse(";"))
                        For Each value As String In newsettings
                            settingnode = xmlConfig.CreateElement("item")
                            settingnode.InnerText = value
                            configNode.AppendChild(settingnode)
                        Next
                    Else
                        settingnode = xmlConfig.CreateTextNode(setting)
                        configNode.AppendChild(settingnode)
                    End If

                    rootNode.AppendChild(configNode)

                    setting = ""

                End If
            Next

            xmlConfig.Save(strPath)
        End Sub

        Private Sub BindSelectedConfig(ByVal strPath As String)
            Dim strCompare As String = treeTools.SelectedNode.Value.ToLower
            Dim strValue As String = strPath.ToLower

            If strValue = strCompare Then
                Dim currentconfig As New List(Of ConfigInfo)

                Dim xmlConfig As New XmlDocument
                xmlConfig.Load(strPath)

                Dim rootNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode("/configuration")
                If Not rootNode Is Nothing Then

                    Dim key As String = Null.NullString
                    Dim setting As String = Null.NullString

                    For Each childnode As XmlNode In rootNode.ChildNodes
                        key = childnode.Attributes("name").Value

                        If childnode.HasChildNodes Then
                            If childnode.ChildNodes.Count = 1 Then
                                If childnode.ChildNodes.Item(0).NodeType = XmlNodeType.Text Then
                                    setting = childnode.InnerText
                                ElseIf childnode.ChildNodes.Item(0).NodeType = XmlNodeType.Element Then
                                    setting = childnode.ChildNodes.Item(0).InnerText
                                End If
                            Else
                                Dim strSetting As String = ""
                                For Each itemnode As XmlNode In childnode.ChildNodes
                                    strSetting += itemnode.InnerText & ";"
                                Next
                                setting = strSetting
                            End If
                        End If

                        If setting.EndsWith(";") Then
                            setting = setting.Substring(0, setting.Length - 1)
                        End If

                        currentconfig.Add(New ConfigInfo(key, setting, False))

                        key = ""
                        setting = ""
                    Next

                    For Each objConfig As ConfigInfo In currentconfig
                        Select Case objConfig.Key.ToLower
                            Case "stripformattingoptions", "contentfilters"
                                Dim ctl As CheckBoxList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), CheckBoxList)

                                If Not ctl Is Nothing Then
                                    Try
                                        If objConfig.Value.Contains(",") Then
                                            For Each strSetting As String In objConfig.Value.Split(Char.Parse(","))
                                                For Each item As ListItem In ctl.Items
                                                    If item.Value.ToLower = strSetting.ToLower Then
                                                        item.Selected = True
                                                        Exit For
                                                    End If
                                                Next
                                            Next
                                        Else
                                            If objConfig.Value.ToLower = "all" Or objConfig.Value.ToLower = "defaultfilters" Then
                                                For Each item As ListItem In ctl.Items
                                                    item.Selected = True
                                                Next
                                            ElseIf objConfig.Value.ToLower = "none" Then
                                                For Each item As ListItem In ctl.Items
                                                    item.Selected = False
                                                Next
                                            Else
                                                For Each item As ListItem In ctl.Items
                                                    If item.Value.ToLower = objConfig.Value.ToLower Then
                                                        item.Selected = True
                                                        Exit For
                                                    End If
                                                Next
                                            End If
                                        End If
                                    Catch
                                    End Try
                                End If

                            Case "toolbarmode"
                                Dim ctl As RadioButtonList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), RadioButtonList)

                                If Not ctl Is Nothing Then
                                    Try
                                        ctl.SelectedValue = objConfig.Value
                                    Catch
                                    End Try
                                End If
                            Case "editmodes"
                                Dim ctl As CheckBoxList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), CheckBoxList)

                                If Not ctl Is Nothing Then
                                    Try
                                        If objConfig.Value.Contains(",") Then
                                            For Each strSetting As String In objConfig.Value.Split(Char.Parse(","))
                                                For Each item As ListItem In ctl.Items
                                                    If item.Value.ToLower = strSetting.ToLower Then
                                                        item.Selected = True
                                                        Exit For
                                                    End If
                                                Next
                                            Next
                                        Else
                                            If objConfig.Value.ToLower = "all" Then
                                                For Each item As ListItem In ctl.Items
                                                    item.Selected = True
                                                Next
                                            Else
                                                For Each item As ListItem In ctl.Items
                                                    If item.Value.ToLower = objConfig.Value.ToLower Then
                                                        item.Selected = True
                                                        Exit For
                                                    End If
                                                Next
                                            End If
                                        End If
                                    Catch
                                    End Try
                                End If
                            Case "imagespath", "mediapath", "documentspath", "flashpath", "silverlightpath", "templatepath"
                                Dim ctl As DropDownList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), DropDownList)

                                If Not ctl Is Nothing Then
                                    Try
                                        ctl.SelectedValue = objConfig.Value
                                    Catch
                                    End Try
                                End If
                            Case "skin", "contentareamode"
                                Dim ctl As DropDownList = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), DropDownList)

                                If Not ctl Is Nothing Then
                                    Try
                                        ctl.SelectedValue = objConfig.Value
                                    Catch
                                    End Try
                                End If
                            Case "borderwidth", "maxflashsize", "height", "maxsilverlightsize", "maxtemplatesize", "maximagesize", "width", "maxdocumentsize", "maxmediasize", "toolswidth"
                                Dim ctl As RadNumericTextBox = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), RadNumericTextBox)

                                If Not ctl Is Nothing Then
                                    Try
                                        ctl.Value = Convert.ToDouble(objConfig.Value.Replace("px", ""))
                                    Catch
                                    End Try
                                End If
                            Case "enableresize", "linksusetabnames", "allowscripts", "showportallinks", "autoresizeheight", "linksuserelativeurls", "dmxintegration", "newlinebr"
                                Dim ctl As CheckBox = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), CheckBox)

                                If Not ctl Is Nothing Then
                                    Try
                                        ctl.Checked = Boolean.Parse(objConfig.Value)
                                    Catch
                                    End Try
                                End If
                            Case Else
                                Dim ctl As TextBox = CType(FindControlRecursive(plhConfig, "ctl_rc_" & objConfig.Key), TextBox)

                                If Not ctl Is Nothing Then
                                    Try
                                        ctl.Text = objConfig.Value
                                    Catch
                                    End Try
                                End If
                        End Select
                    Next
                End If
            End If
        End Sub

        Private Function InitializeDefaultConfig() As List(Of ConfigInfo)
            Dim strPath As String = Server.MapPath(Me.TemplateSourceDirectory & "/ConfigFile/configfile.xml.original.xml")

            Dim config As New List(Of ConfigInfo)

            Dim xmlConfig As New XmlDocument
            xmlConfig.Load(strPath)

            Dim rootNode As XmlNode = xmlConfig.DocumentElement.SelectSingleNode("/configuration")
            If Not rootNode Is Nothing Then

                Dim key As String = Null.NullString
                Dim setting As String = Null.NullString

                For Each childnode As XmlNode In rootNode.ChildNodes

                    key = childnode.Attributes("name").Value

                    If childnode.HasChildNodes Then
                        If childnode.ChildNodes.Count = 1 Then
                            If childnode.ChildNodes.Item(0).NodeType = XmlNodeType.Text Then
                                setting = childnode.InnerText
                            ElseIf childnode.ChildNodes.Item(0).NodeType = XmlNodeType.Element Then
                                setting = childnode.ChildNodes.Item(0).InnerText
                            End If
                        Else
                            Dim strSetting As String = ""
                            For Each itemnode As XmlNode In childnode.ChildNodes
                                strSetting += itemnode.InnerText & ";"
                            Next
                            setting = strSetting
                        End If
                    End If

                    If setting.EndsWith(";") Then
                        setting = setting.Substring(0, setting.Length - 1)
                    End If

                    If Not childnode.Attributes("IsSeparator") Is Nothing Then
                        config.Add(New ConfigInfo(key, "", True))
                    Else
                        config.Add(New ConfigInfo(key, setting, False))
                    End If

                    key = ""
                    setting = ""
                Next

            End If

            Return config
        End Function

        Private Sub BindConfigForm()
            Dim foldersToShow As New ArrayList

            Dim folders As New ArrayList
            folders = DotNetNuke.Common.Utilities.FileSystemUtils.GetFoldersByUser(PortalSettings.PortalId, True, True, "READ")

            plhConfig.Controls.Clear()

            Dim pnlContent As New Panel
            pnlContent.CssClass = "pcContent"

            Dim fsContent As HtmlGenericControl
            Dim i As Integer = 0

            For Each objConfig As ConfigInfo In DefaultConfig
                Dim key As String = objConfig.Key
                Dim value As String = objConfig.Value

                If objConfig.IsSeparator Then
                    If i > 0 Then
                        ' it's currently a separator, so if its not the first item it needs to close the previous 'feildset'
                        pnlContent.Controls.Add(fsContent)
                    End If

                    i += 1

                    pnlContent.Controls.Add(New LiteralControl("<h2 id='Panel-ProviderConfig-" + i.ToString + "' class='dnnFormSectionHead'><a class='dnnSectionExpanded' href="""">" + key + "</a></h2>"))
                    fsContent = New HtmlGenericControl("fieldset")
                Else
                    Dim pnlRow As New Panel ' a row starts here and ends at the right before next, where it is added to the fieldset)
                    pnlRow.CssClass = "dnnFormItem"
                    pnlRow.Controls.Add(BuildLabel(key))

                    Select Case key.ToLower
                        Case "stripformattingoptions"
                            Dim ctl As New CheckBoxList
                            ctl.ID = "ctl_rc_" & key
                            ctl.RepeatColumns = 2
                            ctl.CssClass = "dnnCBItem"

                            For Each objEnum As String In [Enum].GetNames(GetType(Telerik.Web.UI.EditorStripFormattingOptions))
                                If objEnum <> "All" AndAlso objEnum <> "None" Then
                                    ctl.Items.Add(New ListItem(objEnum, objEnum))
                                End If
                            Next

                            pnlRow.Controls.Add(ctl)
                        Case "toolbarmode"
                            Dim ctl As New RadioButtonList
                            ctl.ID = "ctl_rc_" & key
                            ctl.RepeatColumns = 2
                            ctl.CssClass = "dnnFormRadioButtons"

                            For Each objEnum As String In [Enum].GetNames(GetType(Telerik.Web.UI.EditorToolbarMode))
                                ctl.Items.Add(New ListItem(objEnum, objEnum))
                            Next

                            pnlRow.Controls.Add(ctl)
                        Case "editmodes"
                            Dim ctl As New CheckBoxList
                            ctl.ID = "ctl_rc_" & key
                            ctl.RepeatColumns = 1
                            ctl.CssClass = "dnnCBItem"

                            For Each objEnum As String In [Enum].GetNames(GetType(Telerik.Web.UI.EditModes))
                                If objEnum <> "All" Then
                                    ctl.Items.Add(New ListItem(objEnum, objEnum))
                                End If
                            Next

                            pnlRow.Controls.Add(ctl)
                        Case "contentfilters"
                            Dim ctl As New CheckBoxList
                            ctl.ID = "ctl_rc_" & key
                            ctl.RepeatColumns = 2
                            ctl.CssClass = "dnnCBItem"

                            For Each objEnum As String In [Enum].GetNames(GetType(Telerik.Web.UI.EditorFilters))
                                If objEnum <> "None" AndAlso objEnum <> "DefaultFilters" Then
                                    ctl.Items.Add(New ListItem(objEnum, objEnum))
                                End If
                            Next

                            pnlRow.Controls.Add(ctl)
                        Case "imagespath", "mediapath", "documentspath", "flashpath", "silverlightpath", "templatepath"
                            Dim ctl As New DropDownList
                            ctl.ID = "ctl_rc_" & key
                            'ctl.Width = Unit.Pixel(253)
                            ctl.Items.Clear()

                            For Each oFolder As FolderInfo In folders
                                If Not oFolder.FolderPath.ToLower.StartsWith("cache") Then
                                    If oFolder.FolderPath = "" Then
                                        ctl.Items.Add(New ListItem(Localization.GetString("PortalRoot", LocalResourceFile), "/"))
                                    Else
                                        ctl.Items.Add(New ListItem(oFolder.FolderPath, oFolder.FolderPath))
                                    End If
                                End If
                            Next

                            pnlRow.Controls.Add(ctl)
                        Case "skin"
                            Dim ctl As New DropDownList
                            ctl.ID = "ctl_rc_" & key
                            ctl.Items.Add(New ListItem("Default", "Default"))
                            ctl.Items.Add(New ListItem("Black", "Black"))
                            ctl.Items.Add(New ListItem("Sunset", "Sunset"))
                            ctl.Items.Add(New ListItem("Hay", "Hay"))
                            ctl.Items.Add(New ListItem("Forest", "Forest"))
                            ctl.Items.Add(New ListItem("Vista", "Vista"))

                            pnlRow.Controls.Add(ctl)
                        Case "enableresize", "linksusetabnames", "allowscripts", "showportallinks", "autoresizeheight", "linksuserelativeurls", "dmxintegration", "newlinebr"
                            Dim ctl As New CheckBox
                            ctl.ID = "ctl_rc_" & key
                            ctl.CssClass = "dnnCBItem"

                            pnlRow.Controls.Add(ctl)
                        Case "borderwidth", "height", "width", "toolswidth"
                            Dim ctl As New RadNumericTextBox
                            ctl.MinValue = 0
                            ctl.Type = NumericType.Number
                            ctl.ShowSpinButtons = True
                            ctl.IncrementSettings.Step = 1
                            ctl.NumberFormat.DecimalDigits = 0
                            ctl.NumberFormat.GroupSeparator = ""
                            ctl.NumberFormat.GroupSizes = 9
                            ctl.ID = "ctl_rc_" & key
                            ctl.Width = Unit.Pixel(255)

                            pnlRow.Controls.Add(ctl)
                        Case "maxflashsize", "maxsilverlightsize", "maxtemplatesize", "maximagesize", "maxdocumentsize", "maxmediasize"
                            Dim ctl As New RadNumericTextBox
                            ctl.MinValue = 1024
                            ctl.Type = NumericType.Number
                            ctl.ShowSpinButtons = True
                            ctl.IncrementSettings.Step = 1024
                            ctl.NumberFormat.DecimalDigits = 0
                            ctl.NumberFormat.GroupSeparator = ""
                            ctl.NumberFormat.GroupSizes = 9
                            ctl.ID = "ctl_rc_" & key
                            ctl.Width = Unit.Pixel(255)

                            pnlRow.Controls.Add(ctl)
                        Case "contentareamode"
                            Dim ctl As New DropDownList
                            ctl.ID = "ctl_rc_" & key

                            For Each name As String In [Enum].GetNames(GetType(EditorContentAreaMode))
                                If name <> "All" Then
                                    ctl.Items.Add(New ListItem(name, name))
                                End If
                            Next

                            pnlRow.Controls.Add(ctl)
                        Case Else
                            Dim ctl As New TextBox
                            ctl.ID = "ctl_rc_" & key
                            ctl.Text = value

                            pnlRow.Controls.Add(ctl)
                    End Select

                    fsContent.Controls.Add(pnlRow)
                End If
            Next

            pnlContent.Controls.Add(fsContent)

            plhConfig.Controls.Add(pnlContent)
        End Sub

        ''' <summary>
        ''' This method will build a dnn property label (Same as used in the user profile edit area) that can be added to a control.
        ''' </summary>
        ''' <param name="resourceKey"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Private Function BuildLabel(resourceKey As String) As PropertyLabelControl
            Dim propLabel = New PropertyLabelControl()
            propLabel.ID = resourceKey + "_Label"
            propLabel.ShowHelp = True
            propLabel.ResourceKey = resourceKey

            Return propLabel
        End Function

        Private Sub BindFile()
            'ulActions.Visible = True
            Me.pnlEditor.Visible = True
            Me.pnlForm.Visible = False

            Dim configpath As String = Me.treeTools.SelectedNode.Value
            Dim toolspath As String = configpath.ToLower.Replace("config", "tools")

            Try
                Me.treePages.FindNodeByValue(configpath).ExpandParentNodes()
                Me.treePages.FindNodeByValue(configpath).Selected = True
            Catch
            End Try

            If File.Exists(configpath) Then
                BindSelectedConfig(configpath)
                ViewState("EditorConfigPath") = configpath

                cmdUpdate.Enabled = (Not configpath.ToLower.EndsWith("configfile.xml.original.xml"))
                cmdCreate.Enabled = True
                cmdDelete.Enabled = (Not configpath.ToLower.EndsWith("configfile.xml.original.xml") AndAlso Not configpath.ToLower.EndsWith("configfile.xml"))

                If File.Exists(toolspath) Then
                    Dim tr As New StreamReader(toolspath)
                    Me.txtTools.Text = tr.ReadToEnd
                    tr.Close()
                    tr.Dispose()
                Else
                    'load default toolsfile
                    Dim orgPath As String = Server.MapPath(Me.TemplateSourceDirectory & "/ToolsFile/ToolsFile.xml.Original.xml")
                    If File.Exists(orgPath) Then
                        File.Copy(orgPath, toolspath)
                    End If

                    If File.Exists(toolspath) Then
                        Dim tr As New StreamReader(toolspath)
                        Me.txtTools.Text = tr.ReadToEnd
                        tr.Close()
                        tr.Dispose()
                    Else
                        Me.txtTools.Text = "Could not load tools file..."
                    End If
                End If
            End If
        End Sub

        Protected Function FindControlRecursive(ByVal objRoot As Control, ByVal id As String) As Control
            If objRoot.ID = id Then
                Return objRoot
            End If
            For Each c As Control In objRoot.Controls
                Dim t As Control = FindControlRecursive(c, id)
                If Not t Is Nothing Then
                    Return t
                End If
            Next
            Return Nothing
        End Function

        Private Sub LoadPages()
            Me.treePages.Nodes.Clear()

            Dim tc As New TabController
            Dim tabs As TabCollection = tc.GetTabsByPortal(PortalSettings.PortalId)
            For Each oTab In tabs.Values
                If oTab.Level = 0 Then
                    Dim node As New RadTreeNode
                    node.Text = oTab.TabName
                    node.Value = oTab.TabID.ToString
                    treePages.Nodes.Add(node)
                    AddChildren(node)
                End If
            Next
        End Sub

        Private Sub AddChildren(ByRef treenode As RadTreeNode)
            Dim tc As New TabController
            Dim tabs As TabCollection = tc.GetTabsByPortal(PortalSettings.PortalId)
            For Each objTab In tabs.Values
                If objTab.ParentId = Integer.Parse(treenode.Value) Then
                    Dim node As New RadTreeNode
                    node.Text = objTab.TabName
                    node.Value = objTab.TabID.ToString
                    treenode.Nodes.Add(node)
                    AddChildren(node)
                End If
            Next
        End Sub

        Private Sub LoadConfiguration()
            Me.treeTools.Nodes.Clear()

            pnlEditor.Visible = False
            pnlForm.Visible = False

            Dim rootnode As New RadTreeNode("Default Configuration")
            rootnode.Expanded = True

            For Each file As String In System.IO.Directory.GetFiles(Server.MapPath(Me.TemplateSourceDirectory & "/ConfigFile"))
                If file.ToLower.EndsWith("configfile.xml.original.xml") Then

                    rootnode.Value = file

                Else

                    'fix for codeplex issue #187
                    Dim blnAddNode As Boolean = True

                    Dim nodename As String = file.Substring(file.LastIndexOf("\") + 1).Replace(".xml", "")
                    If nodename.StartsWith("ConfigFile") And file.EndsWith(".xml") Then

                        Dim nodeTitle As String = "Everyone"

                        Dim strTargetGroup As String = nodename.Replace("ConfigFile.", "")
                        Dim strTargetPortal As String = ""
                        Dim strTargetTab As String = ""

                        If strTargetGroup.Length > 0 Then

                            If strTargetGroup.ToLower.StartsWith("host") Then
                                rblMode.SelectedValue = "Host"
                                strTargetTab = strTargetGroup.ToLower.Replace("host.", "")
                                nodeTitle = "Host"
                            ElseIf strTargetGroup.ToLower.StartsWith("admin") Then
                                rblMode.SelectedValue = "Admin"
                                strTargetTab = strTargetGroup.ToLower.Replace("admin.", "")
                                nodeTitle = "Admin"
                            ElseIf strTargetGroup.ToLower.StartsWith("registered") Then
                                rblMode.SelectedValue = "Registered"
                                strTargetTab = strTargetGroup.ToLower.Replace("registered.", "")
                                nodeTitle = "Users"
                            Else
                                strTargetTab = strTargetGroup
                            End If

                        End If

                        If strTargetTab.Length > 0 Then
                            If IsNumeric(strTargetTab.ToLower.Replace("tabid.", "")) Then
                                Try
                                    Dim tc As New TabController
                                    Dim t As TabInfo = tc.GetTab(Convert.ToInt32(strTargetTab.ToLower.Replace("tabid.", "")), PortalSettings.PortalId, False)
                                    If Not t Is Nothing Then
                                        If t.PortalID <> PortalSettings.PortalId Then
                                            'fix for codeplex issue #187
                                            blnAddNode = False
                                        End If
                                        nodeTitle += " (Page """ & t.TabName & """ only)"
                                    End If
                                Catch
                                End Try
                            End If
                            If IsNumeric(strTargetTab.ToLower.Replace("portalid.", "")) Then
                                Try
                                    Dim pc As New PortalController
                                    Dim p As PortalInfo = pc.GetPortal(Convert.ToInt32(strTargetTab.ToLower.Replace("portalid.", "")))
                                    If Not p Is Nothing Then
                                        If p.PortalID <> PortalSettings.PortalId Then
                                            'fix for codeplex issue #187
                                            blnAddNode = False
                                        End If
                                        nodeTitle += " (Current Portal only)"
                                    End If
                                Catch
                                End Try
                            End If
                        End If

                        If blnAddNode Then
                            rootnode.Nodes.Add(New RadTreeNode(nodeTitle, file))
                        End If

                    End If

                End If
            Next

            Me.treeTools.Nodes.Add(rootnode)
        End Sub

#End Region

#Region "Optional Interfaces"

        ''' -----------------------------------------------------------------------------
        ''' <summary>
        ''' Registers the module actions required for interfacing with the portal framework
        ''' </summary>
        ''' <value></value>
        ''' <returns></returns>
        ''' <remarks></remarks>
        ''' <history>
        ''' </history>
        ''' -----------------------------------------------------------------------------
        Public ReadOnly Property ModuleActions() As Entities.Modules.Actions.ModuleActionCollection Implements Entities.Modules.IActionable.ModuleActions
            Get
                Dim Actions As New Entities.Modules.Actions.ModuleActionCollection
                'Actions.Add(GetNextActionID, Localization.GetString(Entities.Modules.Actions.ModuleActionType.AddContent, LocalResourceFile), Entities.Modules.Actions.ModuleActionType.AddContent, "", "", EditUrl(), False, Security.SecurityAccessLevel.Edit, True, False)
                Return Actions
            End Get
        End Property

#End Region

    End Class

End Namespace